<!-- modelVersion的公共组件：增删改查; -->
<template>
  <starGenView :title="title">
    <cfg-table v-if="!!this.collectionObject"
      ref="table"
      :columns="columns"
      :actionButtons="actionButtonsCalc"
      :data="collectionObject.records"
      :loading="loading"
      :config="tableConfig"
      :pageSizeOpts="pageSizeOpts"
      :pageNavigation="pageNavigation"
      :queryFormItem="queryFormItem"
      :collapseFormItem="collapseFormItem"
      @loadPage="loadPage"
      @handleClick="(row, index) => $emit('handleClick', row, index)"
      @handleDbClick="(row, index) => $emit('handleDbClick', row, index)"
      @handleSelect="(selection, row) => $emit('handleSelect', selection, row)"
      @handleSelectCancel="(selection, row) => $emit('handleSelectCancel', selection, row)"
      @handleDetail="handleDetail"
      @handleDelete="handleDelete"
      @handleDeleteMultiple="handleDeleteMultiple"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    />
    <cfgCrudModal v-show="modelDrawer.status!=='new'"
      v-bind="modalConfig"
      :classObject="classObject"
      :collectionObject="collectionObject"
      :modelList="modelList"
      :drawer="modelDrawer"
      :fields="modalFormItem"
    />
  </starGenView>
</template>

<script>
import cfgCrudModal from 'public/components/configComp/basic/cfgCrud/cfgCrud-modal'

export default {
  name: 'modelDesign_model',
  components: { cfgCrudModal },
  data() {
    return {
      modelName: `${this.prefix}Model`,
      classObject: null,
      collectionObject: null,
      modelList: [],
      loading: false,
      modalNeedQuery: true,
      pageSizeOpts: [10, 30, 50, 100],
      pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 },
      modalConfig: {
          hasFeatures: true,
          labelWidth: 90,
      },
      modelDrawer: {
        status: 'new',
        show: false
      },
      tableConfig: {
        search: true,
        addButton: false,
        actionEdit: false,       // 显示编辑按钮, 默认为true
        actionDetail: true,      // 显示查看按钮, 默认为true
        actionDelete: true,      // 显示删除按钮, 默认为true
        batchDeleteButton: true, // 显示批量删除按钮
        downloadIcon: true,
        uploadIcon: true,
        uploadUrl: '/',
        tableSizeIcon: true,
        fullscreenIcon: true,
        refreshIcon: true,
        columnSettingIcon: true,
        action: true,
        actionOption: { // action的配置
            width: 280,
        },
        actionButtons: [   // action追加的button
            {
                title: { 'zh-CN': '发布/取消发布', 'en-US': 'publish / cancel publish' },
                color: 'green', eventName: 'actionPublish'
            },
            {
                title: { 'zh-CN': '升级', 'en-US': 'upgrade' }, color: 'orange',
                eventName: 'actionUpgrade'
            },
        ]
      },
    }
  },
  methods:{
    async loadPage(pageNavigation, filter = {}) {
      filter = filter || {}
      this.type && (filter.type = this.type)
      let condition=this.collectionObject.util.getFilter(filter)
      this.loading = true;
      let flag = await this.collectionObject.queryVersionInfoByPage(pageNavigation.pageNumber, pageNavigation.pageSize, condition)

      if (flag) {
        this.pageNavigation.total = this.collectionObject.total;
        this.dataChange('query')
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleSearch(filter) {
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation, filter)
    },
    handleReset() {
      this.isReset = true
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation)
    },
    async getRecord(filter) {
      let flag = await this.classObject.query(this.collectionObject.util.getFilter(filter))
      return flag
    },
    async deleteRecord(classNames) {
      this.loading = true;
      let flag= await this.collectionObject.deleteByClassNames(classNames)

      this.clearTableSelection(flag)
      this.dataChange('delete')
      this.loading = false;
      return flag
    },
    async handleDetail(row, index) {
      let filter = { type: row.type, className: row.className }
      this.loading = true;
      this.modelDrawer.status = 'read'

      if (!this.modalNeedQuery) {
        this.classObject.setRecord(row)
        this.modelDrawer.show = true
        this.loading = false
      }
      else if (await this.getRecord(filter)) {
        this.modelDrawer.show = true
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleDelete(row, index) {
      console.log('handleDelete', this.deleteById);
      if (this.deleteById) {
        this.deleteRecordById([row.id])
      } else if (this.modalConfig.isInstance) {
        this.deleteRecordByInstanceId([row.instanceId])
      } else {
        this.deleteRecord([row.className])
      }
    },
    async handleDeleteMultiple(selection) {
      if (this.deleteById) {
        await this.deleteRecordById(selection.map(item => item.id))
      } else if (this.modalConfig.isInstance) {
        await this.deleteRecordByInstanceId(selection.map(item => item.instanceId))
      } else {
        await this.deleteRecord(selection.map(item => item.className))
      }
    },
    actionPublish(row, index) {
      this.loading = true;
      let className = row.className;
      let version = row.version;
      let published = row.published;
      if(published){
          this.classObject.setUnpublish(className,version).then(flag => {
              if (flag) {
                  this.loadPage(this.pageNavigation, null)
                  this.loading = false;
              }
          })
      } else {
          this.classObject.setPublish(className,version).then(flag => {
              if (flag) {
                  this.loadPage(this.pageNavigation, null)
                  this.loading = false;
              }
          })
      }
    },
    actionUpgrade(row, index) {
      let className = row.className;
      let version =row.version;
      let published = row.published;

      if (published) {
        this.loading = true;
        this.classObject.upgrade(className,version).then(flag => {
            this.loadPage(this.pageNavigation, null)
            this.loading = false;
        })
      }
    },
    clearTableSelection(flag) {
      flag && (this.$refs.table.selection = [])
    },
    dataChange(type) {
      this.$emit('dataChange', type)
    },
  },
  created() {
    this.collectionObject = this.$modelObject.create(`${this.modelName}Collection`);
    this.classObject = this.$modelObject.create(this.modelName)
  },
  beforeMount() {
    this.loadPage(this.pageNavigation)
  },
  props:{
    title:{
      type:String
    },
    type:{
      type:String
    },
    prefix:{
      type:String
    },
  },
  computed: {
    columns() {
      return [
        {
          key: 'type',
          title: this.$t(`model.type`),
          minWidth: 100,
          align: 'center',
          show: true
        },
        {
          key: 'className',
          title: this.$t(`model.className`),
          minWidth: 100,
          align: 'center',
          show: true
        },
        {
          key: 'version',
          title: this.$t(`model.version`),
          minWidth: 50,
          align: 'center',
          show: true,
        },
        {
          key: 'published',
          title: this.$t(`model.published`),
          minWidth: 50,
          align: 'center',
          show: true
        },
        {
          key: 'createTime',
          title: this.$t(`model.createTime`),
          minWidth: 112,
          align: 'center',
          show: true,
        },
        {
          key: 'updateTime',
          title: this.$t(`model.updateTime`),
          minWidth: 112,
          align: 'center',
          show: true,
        },
      ]
    },
    queryFormItem() {
      let item=[
        {
          key: 'type',
          title: this.$t(`model.type`),
          config: {
            type: 'text',
            clearable: true,
          }
        },
        {
        key: 'className',
        title: this.$t(`model.className`),
        config: {
          type: 'text',
          clearable: true,
        }
      }]
      return item;
    },
    // 新增、查看、编辑弹窗，表单展示的字段
    modalFormItem() {
      let items = []
      return items
    },
    collapseFormItem() {
      return this.queryFormItem
    },
    lang() {
      return {
        "en-US": {
          type: 'type',
          className: 'class name',
          instanceName: 'instance name',
          category: 'category',
          eventName: 'event name',
          comments: 'comments',
          version:'version',
          published:'published',
          createTime:'createTime',
          updateTime:'updateTime'
        },
        "zh-CN": {
          type: '所属类型',
          className: '模型类名',
          instanceName: '实例名',
          category: '分类',
          eventName: '事件名称',
          comments:'注释',
          version:'版本',
          published:'已发布',
          createTime:'创建时间',
          updateTime:'更新时间'
        },
      }[this.G_Locale]
    },
    typeList() {
        return this.$modelObject.getModelType(this.modelName.replace('Model', ''));
    },
    actionButtonsCalc() {
      let buttons = [];
      let actionButtons = this.tableConfig.actionButtons

      if (this.tableConfig.action && actionButtons && actionButtons.length) {
        actionButtons.forEach(item => {
          let newItem = {...item}
          newItem.title = item.title[this.G_Locale]
          newItem.event = (row, index) => {
            let res = ''
            if (item.eventName && this[item.eventName]) {
              res = this[item.eventName](row, index)
            }
            if (item.triggerName) {
              res = this.$emit(item.triggerName, item, row, index)
            }
            return res;
          }
          buttons.push(newItem)
        })
      }
      return buttons
    },
  },
}
</script>
